﻿#include "deptcontroller.h"

#include <QJsonDocument>
#include <deptservice.h>
#include <deptvo.h>
#include <qjwtutils.h>
#include <roleservice.h>
#include <user.h>
#include "responesutils.h"

DeptController::DeptController(QObject *parent) : HttpController(parent)
{

}

DeptController::~DeptController()
{

}

void DeptController::route(QString path, QString method, HttpRequest &request, HttpResponse &response)
{
    qDebug() << __FUNCTION__ << path << method;
    if (method == "GET")
    {
        if (path == "list")
        {
            return getList(request, response);
        }
    }
    else if (method == "POST")
    {
        if (path.isEmpty())
        {
            return saveOne(request, response);
        }
    }
    else if (method == "DELETE")
    {
       return deleteOne(path.toULongLong(), response);
    }
    else if (method == "PUT")
    {
        return saveOne(request, response, path.toULongLong());
    }
}

void DeptController::getList(HttpRequest &request, HttpResponse &response)
{
    DeptService objectService;
    QList<DeptVO> list;
    if(!objectService.getDeptVOList(list)){
          return ResponesUtils::erroResponse(response,"数据库异常！");
    }
    QJsonArray jsonArray;
    for(DeptVO &item : list){
        jsonArray.append(item.toJsonObject());
    }
    return ResponesUtils::resultResponse(response,jsonArray);
}

void DeptController::saveOne(HttpRequest &request, HttpResponse &response, uint64_t id)
{
    QByteArray body = request.getBody();
    QJsonParseError parseError;
    QJsonDocument  jsonDocument= QJsonDocument::fromJson(body, &parseError);

    if (parseError.error != QJsonParseError::NoError)
    {
        return ResponesUtils::erroResponse(response,"请求参数JSON结构异常!");
    }

    Dept object;
    object.fromJsonObject(jsonDocument.object());
    if(id != 0){
       object.setId(id);
    }
    DeptService objectService;
    if(!objectService.saveOne(object)){
        return ResponesUtils::erroResponse(response,"数据库异常！");
    }
    //返回结果
    ResponesUtils::resultResponse(response,id == 0 ? "添加成功！" : "修改成功！" );
}

void DeptController::deleteOne(uint64_t id, HttpResponse &response)
{
    if(id == 0 ){
        return ResponesUtils::erroResponse(response,"请指定删除ID！");
    }
    Dept object;
    object.setId(id);
    DeptService objectService;
    if(!objectService.deleteOne(object)){
        return ResponesUtils::erroResponse(response,"数据库异常！");
    }
    //返回结果
    ResponesUtils::resultResponse(response,"删除成功！");
}


